// @flow
import React, { Component } from 'react'
import { Modal, Form, Input, Row, Col, Switch, Table, Button } from 'antd'
// const Option = Select.Option
import R from 'ramda'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

type Props = {
  form: Object,
  removeNode: Function,
  index: number,
  changeContact: Function,
  contactData: Array<Object>,
  customerId: string
}

type States = {
  visible: boolean,
  confirmLoading: boolean,
  customerContacts: Array<Object>,
  selectedRows: Array<Object>
}
class EditContact extends Component {
  props: Props
  state: States
  closeModal: Function
  handleSubmit: Function
  getCustomerContact: Function
  addContact: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      visible: true,
      confirmLoading: false,
      customerContacts: [],
      selectedRows: []
    }
    this.closeModal = this.closeModal.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.getCustomerContact = this.getCustomerContact.bind(this)
    this.addContact = this.addContact.bind(this)
  }

  componentWillMount () {
    this.getCustomerContact(this.props)
  }

  componentWillReceiveProps (nextProps: Object) {
    if (!R.equals(nextProps, this.props)) {
      this.getCustomerContact(nextProps)
    }
  }

  getCustomerContact (props) {
    const { customerId } = props
    // 获取所选客户下的所有联系人
    universalFetch(`${__SERVICE_API__}device/customers/${customerId}/contacts/all`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          customerContacts: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  closeModal () {
    this.setState({
      visible: false
    })
    this.props.removeNode()
  }

  addContact () {
    const { selectedRows } = this.state
    const { index, contactData } = this.props
    let arr = R.clone(contactData)
    selectedRows.map((d, i) => {
      if (d.importance === 'primary') {
        arr.map((dd) => {
          dd['importance'] = 'secondary'
        })
      }
      arr[index + i] = d
    })
    this.props.changeContact(arr)
    this.closeModal()
  }

  handleSubmit () {
    const form = this.props.form
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        confirmLoading: true
      })
      const { index, contactData } = this.props
      let importance = 'secondary'
      if (fieldsValue.importance) {
        importance = 'primary'
      }
      const values = {
        ...fieldsValue,
        importance: importance
      }
      if (importance === 'primary') {
        contactData.map((d) => {
          d['importance'] = 'secondary'
        })
      }
      let arr = R.clone(contactData)
      arr[index] = values
      this.props.changeContact(arr)
      this.setState({
        confirmLoading: false
      }, () => {
        this.closeModal()
      })
    })
  }
  render () {
    const component = this
    const { getFieldDecorator } = this.props.form
    const { visible, confirmLoading, customerContacts, selectedRows } = this.state
    const columns = [{
      title: '名字',
      dataIndex: 'name',
      width: 100
    }, {
      title: '电话号码',
      dataIndex: 'phoneNum',
      width: 100
    }, {
      title: '邮箱',
      dataIndex: 'email',
      width: 100
    }, {
      title: '公司',
      dataIndex: 'companyName',
      width: 100
    }, {
      title: '部门',
      dataIndex: 'departmentName',
      width: 100
    }, {
      title: '微信',
      dataIndex: 'wechat',
      width: 100
    }
    ]

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        component.setState({
          selectedRows: selectedRows
        })
      }
    }
    const btnB = selectedRows.length > 0 ? false : true
    return (
      <Modal
        title='添加联系人'
        width={800}
        visible={visible}
        onCancel={this.closeModal}
        confirmLoading={confirmLoading}
        footer={null}
        >
        <p style={{ paddingBottom: 5, fontWeight: 'bold', fontSize: 14 }}>
          从所属客户中选择联系人添加
          <Button
            type='primary'
            disabled={btnB}
            onClick={this.addContact}
            style={{ marginLeft: 10 }}>
          添加
          </Button>
        </p>
        <Table
          scroll={{ y: 92 }}
          pagination={false}
          size={'small'}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={customerContacts}
        />
        <p style={{ paddingBottom: 5, fontWeight: 'bold', fontSize: 14 }}>
          手动添加联系人
          <Button
            onClick={this.handleSubmit}
            type='primary'
            style={{ marginLeft: 10, marginTop:20 }}>
          添加
          </Button>
        </p>
        <Form style={{ height: 150, overflow: 'auto' }}>
          <Row>
            <Col span={12}>
              <FormItem {...formItemLayout} label='姓名' hasFeedback>
                {getFieldDecorator('name', {
                  rules: [
                    { required: true, message: '请填写姓名', whitespace: true }
                  ]
                })(
                  <Input placeholder='请填写姓名' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='手机号' hasFeedback>
                {getFieldDecorator('phoneNum', {
                  rules: [
                    { required: true, message: '请填写手机号', whitespace: true }
                  ]
                })(
                  <Input placeholder='请填写手机号' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='默认联系人' hasFeedback>
                {getFieldDecorator('importance')(
                  <Switch checkedChildren='是' unCheckedChildren='否' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='微信' hasFeedback>
                {getFieldDecorator('wechat')(
                  <Input placeholder='请填写微信' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='公司' hasFeedback>
                {getFieldDecorator('companyName')(
                  <Input placeholder='请填写公司' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='部门' hasFeedback>
                {getFieldDecorator('departmentName')(
                  <Input placeholder='请填写部门' />
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem {...formItemLayout} label='邮箱' hasFeedback>
                {getFieldDecorator('email', {
                  rules: [
                    { required: true, message: '请填写邮箱' }
                  ]
                })(
                  <Input placeholder='请填写邮箱' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='QQ' hasFeedback>
                {getFieldDecorator('qqNum')(
                  <Input placeholder='请填写QQ' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='单位电话' hasFeedback>
                {getFieldDecorator('businessNum')(
                  <Input placeholder='请填写单位电话' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='住宅电话' hasFeedback>
                {getFieldDecorator('homeNum')(
                  <Input placeholder='请填写住宅电话' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='传真' hasFeedback>
                {getFieldDecorator('fax')(
                  <Input placeholder='请填写传真' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='备注' hasFeedback>
                {getFieldDecorator('remark')(
                  <Input placeholder='请填写备注' />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label='是否是自己添加' hasFeedback style={{ height:0, overflow:'hidden' }}>
                {getFieldDecorator('isSelf', {
                  initialValue:'yes'
                })(
                  <Input />
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(EditContact)
